import javax.tools.ToolProvider;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public class string {
    public static void main(String[] args) {
        var expression = System.getenv("JIANMU_EXPRESSION");
        if (expression == null || expression.isBlank()) {
            System.out.println("error: 表达式不能为空");
            System.exit(1);
        }
        System.out.println("表达式：");
        System.out.println(expression);
        System.out.println();
        var result = formatString(expression);
        System.out.println("输出参数：");
        System.out.println(write(result));
    }

    public static String formatString(String expression) {
        var javaCode = "import java.text.*;\n" +
                        "import java.time.*;\n" +
                        "import java.time.format.*;\n" +
                        "import java.util.*;\n" +
                        "public class StringJava {\n" +
                        "public String run() {\n" +
                        "   return " + expression + ";\n" +
                        "}\n" +
                        "}";
        compile(javaCode);
        return exec();
    }

    public static void compile(String javaCode) {
        var sourceFile = new File("./StringJava.java");
        try {
            Files.writeString(Path.of(sourceFile.getPath()), javaCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
        var javaCompiler = ToolProvider.getSystemJavaCompiler();
        var status = javaCompiler.run(null, null, null, sourceFile.getPath());
        if (status != 0) {
            throw new RuntimeException("error: 编译失败，请检查表达式");
        }
    }

    public static String exec() {
        try {
            var cla = Class.forName("StringJava");
            var o = cla.getDeclaredConstructor().newInstance();
            var method = cla.getMethod("run");
            return (String) method.invoke(o);
        } catch (Exception e) {
            System.out.println("error: 表达式执行失败");
            e.printStackTrace();
            System.exit(1);
        }
        return null;
    }

    public static String write(String result) {
        var result_file = "{\"result\":\"" + result + "\"}";
        FileOutputStream fos;
        try {
            fos = new FileOutputStream("/usr/result_file");
            fos.write(result_file.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            System.out.println("error: 表达式执行结果输出失败");
            e.printStackTrace();
            System.exit(1);
        }
        return result_file;
    }
}
